package com.hunantv.mglive.ui.discovery;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.hunantv.mglive.R;
import com.hunantv.mglive.common.BaseActivity;
import com.hunantv.mglive.common.BaseBar;
import com.hunantv.mglive.common.BuildConfig;
import com.hunantv.mglive.common.Constant;
import com.hunantv.mglive.common.DiscoveryConstants;
import com.hunantv.mglive.common.FormEncodingBuilderEx;
import com.hunantv.mglive.data.ResultModel;
import com.hunantv.mglive.data.VODModel;
import com.hunantv.mglive.data.discovery.CommenData;
import com.hunantv.mglive.data.discovery.DynamicData;
import com.hunantv.mglive.data.discovery.PraiseData;
import com.hunantv.mglive.ui.adapter.DynamicCommenAdapter;
import com.hunantv.mglive.ui.discovery.dynamic.PictureView;
import com.hunantv.mglive.ui.live.ItemEvent;
import com.hunantv.mglive.ui.live.StarDetailActivity;
import com.hunantv.mglive.utils.GlideRoundTransform;
import com.hunantv.mglive.utils.PlayMessageUploadMannager;
import com.hunantv.mglive.utils.ReportUtil;
import com.hunantv.mglive.utils.ShareUtil;
import com.hunantv.mglive.utils.StringUtil;
import com.hunantv.mglive.utils.Toast;
import com.hunantv.mglive.widget.Toast.ConfirmDialog;
import com.hunantv.mglive.widget.media.IjkVideoView;
import com.hunantv.mglive.widget.media.VideoController;

import org.json.JSONException;
import org.json.JSONObject;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import tv.danmaku.ijk.media.player.IMediaPlayer;
import tv.danmaku.ijk.media.player.IjkMediaPlayer;

/**
 * Created by liujianjiu on 2016-4-07.
 * <p/>
 * 动态详情页
 */
public class DetailsActivity extends BaseActivity implements View.OnClickListener, ItemEvent,IMediaPlayer.OnCompletionListener, IMediaPlayer.OnPreparedListener, IMediaPlayer.OnInfoListener, IMediaPlayer.OnErrorListener {
    public static final String KEY_DYNAMIC = "dynamicdata";
    public static final String KEY_DYNAMIC_ID = "dynamic_id";
    private DynamicData mDynamicData;
    private String mDynamicId;
    private List<CommenData> mCommenList;
    private List<PraiseData> mPraiseList;
    private String mVideoPath;
    private int STAR_PAGE_INDEX = 1;
    private int mPageIndex = STAR_PAGE_INDEX, mPagerSize = 100;

    //整体布局控件
    private BaseBar mDynamicDetailTitleBar;
    private RelativeLayout mDynamicDetailEditLay;
    private EditText mDynamicDetailEdit;
    private Button mDynamicDetailEditSend;
    private ListView mDynamicDetailList;
    private DynamicCommenAdapter mDynamicCommenAdapter;
    private ConfirmDialog mConfirmDialog;

    /**
     * 初始化整体布局空件
     */
    private void assignViews() {
        mDynamicDetailTitleBar = (BaseBar) findViewById(R.id.dynamic_detail_title_bar);
        mDynamicDetailEditLay = (RelativeLayout) findViewById(R.id.dynamic_detail_edit_lay);
        mDynamicDetailEdit = (EditText) findViewById(R.id.dynamic_detail_edit);
        mDynamicDetailEditSend = (Button) findViewById(R.id.dynamic_detail_edit_send);
        mDynamicDetailList = (ListView) findViewById(R.id.dynamic_detail_list);

        mDynamicDetailTitleBar.setTitle(getString(R.string.dynamic_title));
        mDynamicDetailTitleBar.mShareIcon.setOnClickListener(this);
        mDynamicDetailEdit.setFocusable(true);
        mDynamicDetailEdit.requestFocus();
    }

    //ListView头部布局控件
    private ViewGroup mDynamicdDetailHead;
    private RelativeLayout mDynamicdDetailTitleRe;
    private ImageView mIvDynamicDetailHead;
    private TextView mTvDynamicDetailName;
    private TextView mTvDynamicDetailTime;
    private ImageView mTvDynamicEx;
    private LinearLayout mDynamicTextContentLay;
    private TextView mTvDynamicDetailContent;
    private PictureView mDynamicDetailImageView;
    private IjkVideoView mDynamicDetailVedioView;
    private FrameLayout mDynamicDetailVedioLay;
    private RelativeLayout mDynamicDetailZanLay;
    private TextView mZanText;
    private ImageView mZanImage1;
    private ImageView mZanImage2;
    private ImageView mZanImage3;
    private ImageView mZanImage4;
    private ImageView mZanImage5;
    private ImageView mZanImage6;
    private LinearLayout mZanAction;
    private ImageView mZanActionImage;
    private View mDeleBu;
    private TextView mZanActionNum;

    private VideoController mController;

    /**
     * 初始化ListView头部布局控件
     */
    private void assignHeadViews() {
        mDynamicdDetailHead = (ViewGroup) LayoutInflater.from(this).inflate(R.layout.layout_dynamic_detail_head, null);
        mDynamicdDetailTitleRe = (RelativeLayout) mDynamicdDetailHead.findViewById(R.id.dynamicd_detail_title_re);
        mIvDynamicDetailHead = (ImageView) mDynamicdDetailHead.findViewById(R.id.iv_dynamic_detail_head);
        mTvDynamicDetailName = (TextView) mDynamicdDetailHead.findViewById(R.id.tv_dynamic_detail_name);
        mTvDynamicDetailTime = (TextView) mDynamicdDetailHead.findViewById(R.id.tv_dynamic_detail_time);
        mTvDynamicEx = (ImageView) mDynamicdDetailHead.findViewById(R.id.tv_dynamic_ex);
        mDynamicTextContentLay = (LinearLayout) mDynamicdDetailHead.findViewById(R.id.dynamic_text_content_lay);
        mTvDynamicDetailContent = (TextView) mDynamicdDetailHead.findViewById(R.id.tv_dynamic_detail_content);
        mDynamicDetailImageView = (PictureView) mDynamicdDetailHead.findViewById(R.id.dynamic_detail_image_view);
        mDynamicDetailVedioLay = (FrameLayout) mDynamicdDetailHead.findViewById(R.id.dynamic_detail_vedio_view);
        mDynamicDetailZanLay = (RelativeLayout) mDynamicdDetailHead.findViewById(R.id.dynamic_detail_zan_lay);
        mZanText = (TextView) mDynamicdDetailHead.findViewById(R.id.zan_text);
        mZanImage1 = (ImageView) mDynamicdDetailHead.findViewById(R.id.zan_image1);
        mZanImage2 = (ImageView) mDynamicdDetailHead.findViewById(R.id.zan_image2);
        mZanImage3 = (ImageView) mDynamicdDetailHead.findViewById(R.id.zan_image3);
        mZanImage4 = (ImageView) mDynamicdDetailHead.findViewById(R.id.zan_image4);
        mZanImage5 = (ImageView) mDynamicdDetailHead.findViewById(R.id.zan_image5);
        mZanImage6 = (ImageView) mDynamicdDetailHead.findViewById(R.id.zan_image6);
        mZanAction = (LinearLayout) mDynamicdDetailHead.findViewById(R.id.zan_action);
        mZanActionImage = (ImageView) mDynamicdDetailHead.findViewById(R.id.zan_action_image);
        mDeleBu = mDynamicdDetailHead.findViewById(R.id.del_dynamic_bu);
        mZanActionNum = (TextView) mDynamicdDetailHead.findViewById(R.id.zan_action_num);

        mZanAction.setOnClickListener(this);
        mDynamicDetailEditSend.setOnClickListener(this);
        mDynamicDetailList.setOnItemClickListener(this);
        mDeleBu.setOnClickListener(this);

        mDynamicDetailList.addHeaderView(mDynamicdDetailHead);
        mDynamicCommenAdapter = new DynamicCommenAdapter(this);
        mDynamicCommenAdapter.setmOnLoadMoreClickListener(new DynamicCommenAdapter.OnLoadMoreClick() {
            @Override
            public void onLoadMore() {
                getMoreList();
            }
        });
        mDynamicDetailList.setAdapter(mDynamicCommenAdapter);

        initDialog();
    }


    /**
     * 更新动态基本信息内容
     */
    private void updateView() {
        if (null == mDynamicData) {
            return;
        }
        //头像
        Glide.with(getContext()).load(mDynamicData.getPhoto()).error(R.drawable.default_icon).placeholder(R.drawable.default_icon).transform(new GlideRoundTransform(getContext(), R.dimen.height_70dp)).into(mIvDynamicDetailHead);
        //昵称
        mTvDynamicDetailName.setText(mDynamicData.getNickName());
        //时间
        mTvDynamicDetailTime.setText(mDynamicData.getDate());
        //内容
        mTvDynamicDetailContent.setText(mDynamicData.getContent());

        //头部跳转链接
        mDynamicdDetailTitleRe.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getContext(), StarDetailActivity.class);
                intent.putExtra(StarDetailActivity.KEY_STAR_ID, mDynamicData.getUid());
                getContext().startActivity(intent);
            }
        });

        //是否为本人动态
        if (!StringUtil.isNullorEmpty(mDynamicData.getUid()) && !StringUtil.isNullorEmpty(getUid()) && mDynamicData.getUid().equals(getUid())) {
            mDeleBu.setVisibility(View.VISIBLE);
        } else {
            mDeleBu.setVisibility(View.GONE);
        }

        //0，文本  1，图片  2，视频
        int type = mDynamicData.getType();
        if (type == 1) {
            mDynamicDetailVedioLay.setVisibility(View.GONE);
            mDynamicDetailImageView.setVisibility(View.VISIBLE);
            mDynamicDetailImageView.notifyChanged(mDynamicData.getImages());
        } else if (type == 2) {
            mDynamicDetailVedioLay.setVisibility(View.VISIBLE);
            mDynamicDetailImageView.setVisibility(View.GONE);

            //添加视频播放插件
            WindowManager windowManager = (WindowManager) getContext().getSystemService((Context.WINDOW_SERVICE));
            int screenWith = windowManager.getDefaultDisplay().getWidth();
            FrameLayout.LayoutParams mVideoViewLP = new FrameLayout.LayoutParams(screenWith, (int) (0.75 * screenWith));
            mDynamicDetailVedioView = new IjkVideoView(getContext());
            mDynamicDetailVedioView.setBackgroundColor(0xFF000000);
            mController = new VideoController(getContext());
            mDynamicDetailVedioView.setController(mController);
            //按比例缩放直播窗体
            mDynamicDetailVedioView.setLayoutParams(mVideoViewLP);

            mDynamicDetailVedioView.setOnCompletionListener(this);
            mDynamicDetailVedioView.setOnPreparedListener(this);
            mDynamicDetailVedioView.setOnErrorListener(this);
            mDynamicDetailVedioView.setOnInfoListener(this);

            MaxSeekBar mSeekBar = new MaxSeekBar(getContext());
            FrameLayout.LayoutParams mSeekBarLP = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT);
            mSeekBarLP.gravity = Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM;
            mSeekBar.setLayoutParams(mSeekBarLP);
            mController.initControllerView(mSeekBar.mSeekHolder.mBtnPause, mSeekBar.mSeekHolder.mSeekbar, null, null);
            mController.show();
            mDynamicDetailVedioLay.addView(mDynamicDetailVedioView);
            mDynamicDetailVedioLay.addView(mSeekBar);

        } else {
            mDynamicDetailVedioLay.setVisibility(View.GONE);
            mDynamicDetailImageView.setVisibility(View.GONE);
        }

    }

    /**
     * 更新赞栏
     */
    private void updatePraiseView() {
        if (mPraiseList != null) {
            //赞头像
            int size = mPraiseList.size();
            switch (size) {
                case 0:
                    mZanImage1.setVisibility(View.GONE);
                    mZanImage2.setVisibility(View.GONE);
                    mZanImage3.setVisibility(View.GONE);
                    mZanImage4.setVisibility(View.GONE);
                    mZanImage5.setVisibility(View.GONE);
                    mZanImage6.setVisibility(View.GONE);

                    break;
                case 1:
                    mZanImage1.setVisibility(View.VISIBLE);
                    mZanImage2.setVisibility(View.GONE);
                    mZanImage3.setVisibility(View.GONE);
                    mZanImage4.setVisibility(View.GONE);
                    mZanImage5.setVisibility(View.GONE);
                    mZanImage6.setVisibility(View.GONE);

                    Glide.with(getContext()).load(mPraiseList.get(0).getPhoto()).error(R.drawable.default_icon).placeholder(R.drawable.default_icon)
                            .transform(new GlideRoundTransform(getContext(), R.dimen.height_27dp)).into(mZanImage1);

                    break;
                case 2:
                    mZanImage1.setVisibility(View.VISIBLE);
                    mZanImage2.setVisibility(View.VISIBLE);
                    mZanImage3.setVisibility(View.GONE);
                    mZanImage4.setVisibility(View.GONE);
                    mZanImage5.setVisibility(View.GONE);
                    mZanImage6.setVisibility(View.GONE);

                    Glide.with(getContext()).load(mPraiseList.get(0).getPhoto()).error(R.drawable.default_icon).placeholder(R.drawable.default_icon)
                            .transform(new GlideRoundTransform(getContext(), R.dimen.height_27dp)).into(mZanImage1);
                    Glide.with(getContext()).load(mPraiseList.get(1).getPhoto()).error(R.drawable.default_icon).placeholder(R.drawable.default_icon)
                            .transform(new GlideRoundTransform(getContext(), R.dimen.height_27dp)).into(mZanImage2);


                    break;
                case 3:
                    mZanImage1.setVisibility(View.VISIBLE);
                    mZanImage2.setVisibility(View.VISIBLE);
                    mZanImage3.setVisibility(View.VISIBLE);
                    mZanImage4.setVisibility(View.GONE);
                    mZanImage5.setVisibility(View.GONE);
                    mZanImage6.setVisibility(View.GONE);

                    Glide.with(getContext()).load(mPraiseList.get(0).getPhoto()).error(R.drawable.default_icon).placeholder(R.drawable.default_icon)
                            .transform(new GlideRoundTransform(getContext(), R.dimen.height_27dp)).into(mZanImage1);
                    Glide.with(getContext()).load(mPraiseList.get(1).getPhoto()).error(R.drawable.default_icon).placeholder(R.drawable.default_icon)
                            .transform(new GlideRoundTransform(getContext(), R.dimen.height_27dp)).into(mZanImage2);
                    Glide.with(getContext()).load(mPraiseList.get(2).getPhoto()).error(R.drawable.default_icon).placeholder(R.drawable.default_icon)
                            .transform(new GlideRoundTransform(getContext(), R.dimen.height_27dp)).into(mZanImage3);

                    break;
                case 4:
                    mZanImage1.setVisibility(View.VISIBLE);
                    mZanImage2.setVisibility(View.VISIBLE);
                    mZanImage3.setVisibility(View.VISIBLE);
                    mZanImage4.setVisibility(View.VISIBLE);
                    mZanImage5.setVisibility(View.GONE);
                    mZanImage6.setVisibility(View.GONE);


                    Glide.with(getContext()).load(mPraiseList.get(0).getPhoto()).error(R.drawable.default_icon).placeholder(R.drawable.default_icon)
                            .transform(new GlideRoundTransform(getContext(), R.dimen.height_27dp)).into(mZanImage1);
                    Glide.with(getContext()).load(mPraiseList.get(1).getPhoto()).error(R.drawable.default_icon).placeholder(R.drawable.default_icon)
                            .transform(new GlideRoundTransform(getContext(), R.dimen.height_27dp)).into(mZanImage2);
                    Glide.with(getContext()).load(mPraiseList.get(2).getPhoto()).error(R.drawable.default_icon).placeholder(R.drawable.default_icon)
                            .transform(new GlideRoundTransform(getContext(), R.dimen.height_27dp)).into(mZanImage3);
                    Glide.with(getContext()).load(mPraiseList.get(3).getPhoto()).error(R.drawable.default_icon).placeholder(R.drawable.default_icon)
                            .transform(new GlideRoundTransform(getContext(), R.dimen.height_27dp)).into(mZanImage3);

                    break;
                case 5:
                    mZanImage1.setVisibility(View.VISIBLE);
                    mZanImage2.setVisibility(View.VISIBLE);
                    mZanImage3.setVisibility(View.VISIBLE);
                    mZanImage4.setVisibility(View.VISIBLE);
                    mZanImage5.setVisibility(View.VISIBLE);
                    mZanImage6.setVisibility(View.GONE);

                    Glide.with(getContext()).load(mPraiseList.get(0).getPhoto()).error(R.drawable.default_icon).placeholder(R.drawable.default_icon)
                            .transform(new GlideRoundTransform(getContext(), R.dimen.height_27dp)).into(mZanImage1);
                    Glide.with(getContext()).load(mPraiseList.get(1).getPhoto()).error(R.drawable.default_icon).placeholder(R.drawable.default_icon)
                            .transform(new GlideRoundTransform(getContext(), R.dimen.height_27dp)).into(mZanImage2);
                    Glide.with(getContext()).load(mPraiseList.get(2).getPhoto()).error(R.drawable.default_icon).placeholder(R.drawable.default_icon)
                            .transform(new GlideRoundTransform(getContext(), R.dimen.height_27dp)).into(mZanImage3);
                    Glide.with(getContext()).load(mPraiseList.get(3).getPhoto()).error(R.drawable.default_icon).placeholder(R.drawable.default_icon)
                            .transform(new GlideRoundTransform(getContext(), R.dimen.height_27dp)).into(mZanImage4);
                    Glide.with(getContext()).load(mPraiseList.get(4).getPhoto()).error(R.drawable.default_icon).placeholder(R.drawable.default_icon)
                            .transform(new GlideRoundTransform(getContext(), R.dimen.height_27dp)).into(mZanImage5);
                    break;

                default:
                    mZanImage1.setVisibility(View.VISIBLE);
                    mZanImage2.setVisibility(View.VISIBLE);
                    mZanImage3.setVisibility(View.VISIBLE);
                    mZanImage4.setVisibility(View.VISIBLE);
                    mZanImage5.setVisibility(View.VISIBLE);
                    mZanImage6.setVisibility(View.VISIBLE);

                    Glide.with(getContext()).load(mPraiseList.get(0).getPhoto()).error(R.drawable.default_icon).placeholder(R.drawable.default_icon)
                            .transform(new GlideRoundTransform(getContext(), R.dimen.height_27dp)).into(mZanImage1);
                    Glide.with(getContext()).load(mPraiseList.get(1).getPhoto()).error(R.drawable.default_icon).placeholder(R.drawable.default_icon)
                            .transform(new GlideRoundTransform(getContext(), R.dimen.height_27dp)).into(mZanImage2);
                    Glide.with(getContext()).load(mPraiseList.get(2).getPhoto()).error(R.drawable.default_icon).placeholder(R.drawable.default_icon)
                            .transform(new GlideRoundTransform(getContext(), R.dimen.height_27dp)).into(mZanImage3);
                    Glide.with(getContext()).load(mPraiseList.get(3).getPhoto()).error(R.drawable.default_icon).placeholder(R.drawable.default_icon)
                            .transform(new GlideRoundTransform(getContext(), R.dimen.height_27dp)).into(mZanImage4);
                    Glide.with(getContext()).load(mPraiseList.get(4).getPhoto()).error(R.drawable.default_icon).placeholder(R.drawable.default_icon)
                            .transform(new GlideRoundTransform(getContext(), R.dimen.height_27dp)).into(mZanImage5);
                    Glide.with(getContext()).load(mPraiseList.get(5).getPhoto()).error(R.drawable.default_icon).placeholder(R.drawable.default_icon)
                            .transform(new GlideRoundTransform(getContext(), R.dimen.height_27dp)).into(mZanImage6);
                    break;

            }

            //赞数量状态
            for (PraiseData data : mPraiseList) {
                if (data.getUid().equals(getUid())) {
                    mZanActionNum.setText(" " + mDynamicData.getPraiseCount());
                    mZanActionImage.setImageResource(R.drawable.max_dynamic_praise_on);
                    mZanActionNum.setTextColor(0xFFFF7919);
                    return;
                }
            }
            mZanActionNum.setText(" " + mDynamicData.getPraiseCount());
            mZanActionImage.setImageResource(R.drawable.max_dynamic_praise_off);
            mZanActionNum.setTextColor(0xFF999999);
        } else {
            mZanImage1.setVisibility(View.GONE);
            mZanImage2.setVisibility(View.GONE);
            mZanImage3.setVisibility(View.GONE);
            mZanImage4.setVisibility(View.GONE);
            mZanImage5.setVisibility(View.GONE);
            mZanImage6.setVisibility(View.GONE);
            mZanActionImage.setImageResource(R.drawable.max_dynamic_praise_off);
            mZanActionNum.setTextColor(0xFF999999);
            mZanActionNum.setText(0 + "");
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);

        setContentView(R.layout.activity_dynamic_detail);
        assignViews();
        assignHeadViews();

        IjkMediaPlayer.loadLibrariesOnce(null);
        IjkMediaPlayer.native_profileBegin("libijkplayer.so");

        try {
            mDynamicData = (DynamicData) getIntent().getSerializableExtra(KEY_DYNAMIC);
        } catch (Exception e) {
            e.printStackTrace();
            mDynamicData = null;
        }
        if (null == mDynamicData) {
            String id = "";
            try {
                id = getIntent().getStringExtra(KEY_DYNAMIC_ID);
            } catch (Exception e) {
                e.printStackTrace();
            }
            mDynamicId = id;
            if (StringUtil.isNullorEmpty(mDynamicId)) {
                finish();
            }
            requestDate(mDynamicId, BuildConfig.URL_DYNAMIC_GET_DETAIL);
        } else {
            mDynamicId = mDynamicData.getDynamicId();
            loadData();
            updateView();
        }

    }

    int mProgress;//播放进度

    @Override
    protected void onStop() {
        if (mDynamicData != null && mDynamicData.getType() == 2) {//暂停播放
            mProgress = mDynamicDetailVedioView.getCurrentPosition();
            if(mDynamicDetailVedioView.isPlaying()){
                mDynamicDetailVedioView.pause();
                //停止视频卡顿信息上报
                PlayMessageUploadMannager.getInstance().stopUploadMessage();
                //完成上报
                PlayMessageUploadMannager.getInstance().doneUpMessage();
            }

        }
        super.onStop();
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (mDynamicData != null && mDynamicData.getType() == 2) {
            if (!StringUtil.isNullorEmpty(mVideoPath) && mDynamicDetailVedioView != null && mProgress > 0) {//重新播放
                Map<String, String> params = new HashMap<>();
                params.put("auid", mDynamicData.getUid());
                params.put("mid", mDynamicData.getVideo().getUrl());
                params.put("ap", "1");
                mDynamicDetailVedioView.setVideoPath(mVideoPath, params, IjkVideoView.VideoType.vod);
                mDynamicDetailVedioView.seekTo(mProgress);
                mDynamicDetailVedioView.start();

                Log.i("PlayStadus", "start");
                //开启上报卡顿信息
                String host = StringUtil.getUrlHost(mVideoPath);
                String path = "";
                if(!StringUtil.isNullorEmpty(host)){
                    path = mVideoPath.substring(host.length()+7);
                }
                try {
                    path = URLEncoder.encode(path, "UTF-8");
                }catch (Exception e){
                    e.printStackTrace();
                }
                PlayMessageUploadMannager.getInstance().startUploadMessage(host, path, "0");
            }
        }
    }

    @Override
    protected void onDestroy() {
        try {
            IjkMediaPlayer.native_profileEnd();
        } catch (Exception e) {

        }
        if (mController != null) {
            mController.onDestory();
        }
        super.onDestroy();
    }


    /**
     * 通知删除动态
     */
    public void notifyDelDynamic(String dynamicId) {
        Intent intent = new Intent(DiscoveryConstants.ACTION_DEL_DYNAMIC);
        intent.putExtra(DiscoveryConstants.KEY_DEL_DYNAMIC, dynamicId);
        sendBroadcast(intent);
    }

    /**
     * 通知删除动态
     */
    public void notifyDynamicUpdate() {
        Intent intent = new Intent(DiscoveryConstants.ACTION_UPDATE_DYNAMIC);
        sendBroadcast(intent);
    }

    @Override
    public void onClick(View v) {
        if (v == mDynamicDetailEditSend) {//评论
            if (!isLogin()) {
                jumpToLogin("登录以后才可以评论哦~");
            } else {
                if (StringUtil.isNullorEmpty(mDynamicDetailEdit.getText().toString())) {
                    return;
                }
                addCommen(BuildConfig.URL_DYNAMIC_ADD_COMMEN, mDynamicId, mDynamicDetailEdit.getText().toString());
                mDynamicDetailEdit.setText("");
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(mDynamicDetailEdit.getWindowToken(), 0);
            }
        } else if (v == mZanAction) {//赞
            if (!isLogin()) {
                jumpToLogin("登录以后才可以赞哦~");
            } else {
                if (null == mPraiseList || mDynamicData == null) {
                    return;
                }

                for (PraiseData data : mPraiseList) {
                    if (data.getUid().equals(getUid())) {
                        long praiseCount = mDynamicData.getPraiseCount() - 1;
                        if(praiseCount < 0){
                            praiseCount = 0;
                        }
                        Toast.makeText(getContext(), "取消赞..", Toast.LENGTH_SHORT).show();
                        removePraise(BuildConfig.URL_DYNAMIC_DEL_PRAISE, mDynamicId, data);
                        mDynamicData.setPraiseCount(praiseCount);
                        mZanActionNum.setText(" " + praiseCount);
                        mZanActionImage.setImageResource(R.drawable.max_dynamic_praise_off);
                        mZanActionNum.setTextColor(0xFF999999);
                        return;
                    }
                }
                Toast.makeText(getContext(), "已赞", Toast.LENGTH_SHORT).show();
                addPraise(BuildConfig.URL_DYNAMIC_ADD_PRAISE, mDynamicId);

                long praiseCount = mDynamicData.getPraiseCount() + 1;
                if(praiseCount < 0){
                    praiseCount = 0;
                }
                mDynamicData.setPraiseCount(praiseCount);
                mZanActionNum.setText(" " + praiseCount);
                mZanActionImage.setImageResource(R.drawable.max_dynamic_praise_on);
                mZanActionNum.setTextColor(0xFFFF7919);
            }
        }
//        else if (v == mDeleBu) {//删除动态
//            if (!isLogin()) {
//                jumpToLogin("登录以后才可以删除哦~");
//            } else {
//                if (!mConfirmDialog.isShowing()) {
//                    mConfirmDialog.show();
//                }
//            }
//
//        }
        else if (v == mDynamicDetailTitleBar.mShareIcon) {//分享
            share();
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        position--;//减去头部占用的position
        CommenData commenData = (CommenData) (mDynamicCommenAdapter.getItem(position));
        if (commenData != null) {//@某人
            mDynamicDetailEdit.setText("@" + commenData.getNickName() + " ");
            mDynamicDetailEdit.setFocusable(true);
            mDynamicDetailEdit.requestFocus();
            mDynamicDetailEdit.setSelection(mDynamicDetailEdit.getText().length());
            InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.showSoftInput(mDynamicDetailEdit, InputMethodManager.SHOW_FORCED);
        }
    }

    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
        return false;
    }

    ShareUtil mShareUtil;

    private void share() {
        if (null != mDynamicData) {
            if (null == mShareUtil) {
                mShareUtil = new ShareUtil(this);
            }
            mShareUtil.share(getUid(), getToken(), ShareUtil.TYPE_DYNAMIC, mDynamicData.getDynamicId(), mDynamicData.getUid(), "", "");

        }
    }

    /**
     * 获取更多评论列表
     */
    private void getMoreList() {
        mPageIndex++;
        requestDate(mDynamicId, mPageIndex, mPagerSize, BuildConfig.URL_DYNAMIC_COMMEN_LIST);
    }

    /**
     * 请求数据
     */
    private void loadData() {
        if (null == mDynamicData) {
            return;
        }
        if (null == mCommenList) {
            mCommenList = new ArrayList<>();
        }
        if (null == mPraiseList) {
            mPraiseList = new ArrayList<>();
        }
        //请求评论
        requestDate(mDynamicId, mPageIndex, mPagerSize, BuildConfig.URL_DYNAMIC_COMMEN_LIST);
        //请求赞
        requestDate(mDynamicId, mPageIndex, 8, BuildConfig.URL_DYNAMIC_PRAISE_LIST);
        //请求视频地址
        if (null != mDynamicData.getVideo() && !StringUtil.isNullorEmpty(mDynamicData.getVideo().getUrl())) {
            requestData(mDynamicData.getVideo().getUrl());
        }
    }

    /**
     * Post请求视频地址
     *
     * @param url 视频文件名
     */
    private void requestData(String url) {
        Map<String, String> param = new FormEncodingBuilderEx()
                .add(Constant.KEY_MEDIAID, url)
                .add(Constant.KEY_RATE, "SD")
                .add(Constant.KEY_TYPE, "key")
                .add(Constant.KEY_USER_ID, getUid())
                .add(Constant.KEY_USER_ID, getToken())
                .build();

        post(BuildConfig.URL_GET_VIDEO_URL, param);
    }

    /**
     * 添加评论
     *
     * @param url
     * @param dynamicId
     * @param content
     */
    private void addCommen(String url, String dynamicId, String content) {
        Map<String, String> param = new FormEncodingBuilderEx().add("dynamicId", dynamicId + "").add("token", getToken()).add("uid", getUid()).add("content", content).build();
        post(url, param);
        if (null == mCommenList) {
            mCommenList = new ArrayList<>();
        }
    }

    /**
     * 添加赞
     *
     * @param url
     * @param dynamicId
     */
    private void addPraise(String url, String dynamicId) {
        Map<String, String> param = new FormEncodingBuilderEx().add("dynamicId", dynamicId + "").add("token", getToken()).add("uid", getUid()).build();
        post(url, param);
        if (null == mPraiseList) {
            mPraiseList = new ArrayList<>();
        }
        PraiseData data = new PraiseData();
        data.setDynamicId(mDynamicId);
        data.setUid(getUid());
        data.setNickName(getUserInfo().getNickName());
        data.setPhoto(getUserInfo().getPhoto());
        mPraiseList.add(0, data);
        updatePraiseView();
    }

    /**
     * 取消赞
     *
     * @param url
     * @param dynamicId
     */
    private void removePraise(String url, String dynamicId, PraiseData data) {
        Map<String, String> param = new FormEncodingBuilderEx().add("dynamicId", dynamicId + "").add("token", getToken()).add("uid", getUid()).build();
        post(url, param);
        if (null != mPraiseList) {
            mPraiseList.remove(data);
            updatePraiseView();
        }
    }

    /**
     * 取消赞
     *
     * @param url
     * @param dynamicId
     */
    private void removeDynamic(String url, String dynamicId) {
        Map<String, String> param = new FormEncodingBuilderEx().add("dynamicId", dynamicId + "").add("token", getToken()).add("uid", getUid()).build();
        post(url, param);
    }

    /**
     * Post请求数据
     *
     * @param pageNum  页数
     * @param pageSize
     */
    private void requestDate(String dynamicId, int pageNum, int pageSize, String url) {
        Map<String, String> param = new FormEncodingBuilderEx().add("dynamicId", dynamicId + "").add("page", pageNum + "").add("pageSize", pageSize + "").build();
        post(url, param);
    }

    /**
     * 获取动态详情数据
     *
     * @param dynamicId
     * @param url
     */
    private void requestDate(String dynamicId, String url) {
        Map<String, String> param = new FormEncodingBuilderEx().add("dynamicId", dynamicId + "").add("uid", getUid()).add("token", getToken()).build();
        post(url, param);
    }

    @Override
    public void onSucceed(String url, ResultModel resultModel) throws JSONException {
        super.onSucceed(url, resultModel);
        if (url.contains(BuildConfig.URL_DYNAMIC_COMMEN_LIST)) {
            try {
                List<CommenData> arrray = JSON.parseArray(resultModel.getData(), CommenData.class);
                if (null == mCommenList) {
                    mCommenList = new ArrayList<>();
                }
                mCommenList.addAll(arrray);
                if (arrray.size() < mPagerSize) {
                    mDynamicCommenAdapter.setData(mCommenList, false);
                } else {
                    mDynamicCommenAdapter.setData(mCommenList, true);
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (url.contains(BuildConfig.URL_DYNAMIC_PRAISE_LIST)) {
            try {
                List<PraiseData> arrray = JSON.parseArray(resultModel.getData(), PraiseData.class);
                if (null == mPraiseList) {
                    mPraiseList = new ArrayList<>();
                }
                mPraiseList.addAll(arrray);
                updatePraiseView();
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (url.contains(BuildConfig.URL_GET_VIDEO_URL)) {
            VODModel vod = JSON.parseObject(resultModel.getData(),VODModel.class);
            if(vod != null){
                if(vod.isMgtvType()){
                    getVodUrl(vod.getPlayUrl());
                }else{
                    playVod(vod.getPlayUrl());
                }
            }
        } else if(!StringUtil.isNullorEmpty(mVodRequestUrl) && mVodRequestUrl.equals(url))
        {
            try {
                JSONObject jsonData = new JSONObject(resultModel.getData());
                playVod(jsonData.getString("info"));

                String param = StringUtil.urlJoint(mVodRequestUrl, resultModel.getParam());
                ReportUtil.instance().report(mVodRequestUrl, param, "0", "2", "", true);

                mVodRequestUrl = null;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else if (url.contains(BuildConfig.URL_DYNAMIC_ADD_PRAISE) || url.contains(BuildConfig.URL_DYNAMIC_DEL_PRAISE)) {
            notifyDynamicUpdate();
        } else if (url.contains(BuildConfig.URL_DYNAMIC_ADD_COMMEN)) {
            //请求评论
            mPageIndex = 1;
            mCommenList = null;
            requestDate(mDynamicData.getDynamicId(), mPageIndex, mPagerSize, BuildConfig.URL_DYNAMIC_COMMEN_LIST);
            notifyDynamicUpdate();
        } else if (url.contains(BuildConfig.URL_DYNAMIC_GET_DETAIL)) {
            try {
                mDynamicData = JSON.parseObject(resultModel.getData(), DynamicData.class);
                if (null != mDynamicData) {
                    mDynamicId = mDynamicData.getDynamicId();
                    loadData();
                    updateView();
                } else {
                    finish();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    //点播类型为MGTV时缓存请求URl
    private String mVodRequestUrl;

    private void getVodUrl(String url){
        mVodRequestUrl = url;
        if(!StringUtil.isNullorEmpty(mVodRequestUrl)){
            get(url,null);
        }
    }

    private void playVod(String url){
        mVideoPath = url;
        Map<String, String> params = new HashMap<>();
        params.put("auid", mDynamicData.getUid());
        params.put("mid", mDynamicData.getVideo().getUrl());
        params.put("ap", "1");
        mDynamicDetailVedioView.setVideoPath(mVideoPath, params, IjkVideoView.VideoType.vod);
        mDynamicDetailVedioView.requestFocus();
        mDynamicDetailVedioView.start();

        Log.i("PlayStadus", "start");
        //开启上报卡顿信息
        String host = StringUtil.getUrlHost(mVideoPath);
        String path = "";
        if(!StringUtil.isNullorEmpty(host)){
            path = mVideoPath.substring(host.length()+7);
        }
        try {
            path = URLEncoder.encode(path, "UTF-8");
        }catch (Exception e){
            e.printStackTrace();
        }
        PlayMessageUploadMannager.getInstance().startUploadMessage(host, path, "0");
    }

    @Override
    public void onFailure(String url, ResultModel resultModel) {
        super.onFailure(url, resultModel);
        if (url != null && url.contains(BuildConfig.URL_DYNAMIC_GET_DETAIL)) {
            mPageIndex--;
            if (mPageIndex < 1) {
                mPageIndex = 1;
            }
        }
        if(!StringUtil.isNullorEmpty(mVodRequestUrl) && mVodRequestUrl.equals(url)) {
            try {
                //把code转成2开头
                String responseCode = resultModel.getResponseCode();
                if(!StringUtil.isNullorEmpty(responseCode)){
                    String subFirst = responseCode.substring(0,1);
                    responseCode = responseCode.replace(subFirst,"2");
                }
                String param = StringUtil.urlJoint(mVodRequestUrl, resultModel.getParam());
                ReportUtil.instance().report(mVodRequestUrl, param, "0", "2", responseCode, false);

                mVodRequestUrl = null;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onCompletion(IMediaPlayer mp) {

        //停止视频卡顿信息上报
        PlayMessageUploadMannager.getInstance().stopUploadMessage();
        //完成上报
        PlayMessageUploadMannager.getInstance().doneUpMessage();
    }

    @Override
    public boolean onError(IMediaPlayer mp, int what, int extra) {

        //出错上报
        PlayMessageUploadMannager.getInstance().errUpMessage(what,extra);
        Log.i("LiveVideo", "OnErr--->what--->" + what + "extra--->" + extra);

        return false;
    }

    @Override
    public boolean onInfo(IMediaPlayer mp, int what, int extra) {
        switch (what) {
            case IMediaPlayer.MEDIA_INFO_BUFFERING_START:

                Log.i("LiveVideo", "OnPuse");
                PlayMessageUploadMannager.getInstance().addPuseCount();
                break;
            case IMediaPlayer.MEDIA_INFO_BUFFERING_END:
                PlayMessageUploadMannager.getInstance().doErrCount();
                break;
        }
        return false;
    }

    @Override
    public void onPrepared(IMediaPlayer mp) {

        Log.i("Play","onPrepared");

    }

    private void initDialog() {
        mConfirmDialog = new ConfirmDialog(getContext(), R.string.tips_dynamic_delete, R.string.ok_1, R.string.cancel);
        mConfirmDialog.setClicklistener(new ConfirmDialog.ClickListenerInterface() {
            @Override
            public void doConfirm() {
                mConfirmDialog.dismiss();
            }

            @Override
            public void doCancel() {
                mConfirmDialog.cancel();
            }
        });
    }
}